package com.cn.dlwy.mapzone.view;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.PopupWindow;

public class PopupWindows {

	// popup显示的背景
	protected Drawable mBackground = null;
	protected Context mContext;
	// popup中显示的内容
	protected View mRootView;
	// popup对象
	protected PopupWindow mWindow;
	// 系统窗口管理对象

	public PopupWindows(Context context) {
		mContext = context;
		mWindow = new PopupWindow(context);
		mWindow.setTouchInterceptor(new View.OnTouchListener() {
			public boolean onTouch(View view, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
					mWindow.dismiss();
					return true;
				}
				return false;
			}
		});
	}

	public void dismiss() {
		mWindow.dismiss();
	}

	public void showAsDropDown(View view) {
		mWindow.showAsDropDown(view);
	}

	public void showAsDropDown(View view, int xoff, int yoff) {
		mWindow.showAsDropDown(view, xoff, yoff);
	}

	public void showAtLocation(View parent, int gravity, int x, int y) {
		mWindow.showAtLocation(parent, gravity, x, y);
	}

	public void setLayoutParams(int x, int y) {
		mWindow.setWidth(x);
		mWindow.setHeight(y);
	}

	protected void preShow() {
		if (mRootView == null) {
			throw new IllegalStateException(
					"setContentView was not called with a view to display.");
		}
		if (mBackground == null) {
			mWindow.setBackgroundDrawable(new BitmapDrawable());
			mWindow.setWidth(LayoutParams.WRAP_CONTENT);
			mWindow.setHeight(LayoutParams.WRAP_CONTENT);
			mWindow.setTouchable(true);
			mWindow.setFocusable(true);
			mWindow.setOutsideTouchable(true);
			mWindow.setContentView(mRootView);
		} else {
			mWindow.setBackgroundDrawable(mBackground);
		}
	}

	public void setBackgroundDrawable(Drawable paramDrawable) {
		mBackground = paramDrawable;
	}

	public void setContentView(int resID) {
		setContentView(((LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
				resID, null));
	}

	public void setContentView(View view) {
		mRootView = view;
		mWindow.setContentView(view);
	}

	public void setOnDismissListener(PopupWindow.OnDismissListener listener) {
		mWindow.setOnDismissListener(listener);
	}
}
